package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.DeviceTypeMapper;
import com.indusfo.spc.pojo.DeviceType;
import com.indusfo.spc.pojo.Inspect;
import com.indusfo.spc.service.DeviceTypeService;
import com.indusfo.spc.vo.JSONObject;
import com.indusfo.spc.vo.XCommonUtil;
import com.indusfo.spc.vo.XTreeNode;
import com.indusfo.spc.vo.XTreeUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 *@Description 设备类型service
 *@Author louk
 *@Date 14:15 2019/12/10
*/
@Service
public class DeviceTypeServiceImpl implements DeviceTypeService {


    //日志记录
    private static final Logger logger = LoggerFactory.getLogger(DeviceTypeServiceImpl.class);

    @Resource
    private DeviceTypeMapper deviceTypeMapper;

    /**
     * 新增
     * @param deviceType
     * @return
     */
    @Override
    public JSONObject insertDeviceType(DeviceType deviceType) {
        try{
            //判断其是否存在父ID
            if(deviceType.getDeviceTypePid()==null  || "".equals(deviceType.getDeviceTypePid())){
                deviceType.setDeviceTypePid(0);
            }
            String checkElementResult = checkElement(deviceType);
            if(!StringUtils.isEmpty(checkElementResult)){
                return JSONObject.build(JSONObject.ERROR,checkElementResult);
            }
            Integer row = deviceTypeMapper.insertDeviceType(deviceType);
            if(row == 0) {
                return JSONObject.build(JSONObject.ERROR,"新增物料类型失败");
            }
            return JSONObject.oK("新增成功", deviceType.getDeviceTypeId());
        }catch (GlobalException e){
            logger.error(e.getMessage());
            return JSONObject.build(JSONObject.ERROR, e.getMessage());
        }
    }

    /**
     * 编辑
     * @param deviceType
     * @return
     */
    @Override
    public JSONObject updateDeviceType(DeviceType deviceType) {
        try{
            if(deviceType.getDeviceTypeId()==null || "".equals(deviceType.getDeviceTypeId())){
                throw new ModifyFailedException("请选择设备类型");
            }
            //判断其是否存在父ID
            if(deviceType.getDeviceTypePid()==null  || "".equals(deviceType.getDeviceTypePid())){
                deviceType.setDeviceTypePid(0);
            }
            String checkElementResult = checkElement(deviceType);
            if(!StringUtils.isEmpty(checkElementResult)){
                return JSONObject.build(JSONObject.SUCCESS,checkElementResult);
            }

            Integer row = deviceTypeMapper.updateDeviceType(deviceType);
            if(row == 0) {
                throw new ModifyFailedException("更新物料类型失败");
            }
            return JSONObject.oK("更新成功", deviceType.getDeviceTypeId());


        }catch (GlobalException e){
            logger.error(e.getMessage());
            return JSONObject.build(JSONObject.ERROR, e.getMessage());
        }
    }

    /**
     * 删除
     * @param deviceTypeId
     * @param dataState
     * @return
     */
    @Override
    public JSONObject defineDeviceType(Integer deviceTypeId,Integer  dataState){
        try {
            //1.校验
            if(deviceTypeId == null) {
                return JSONObject.build(JSONObject.ERROR,"物料类型id不能为空");
            }
            if(dataState == null) {
                return JSONObject.build(JSONObject.ERROR,"物料类型状态不能为空");
            }
            if(dataState !=1 && dataState!=2 && dataState!=3) {
                return JSONObject.build(JSONObject.ERROR,"数据状态错误");
            }
            int flag = deviceTypeMapper.countByDeviceTypePid(deviceTypeId);
            if(flag>0){
                return JSONObject.build(JSONObject.ERROR,"所选设备类别下仍包含子类无法删除");
            }
            //判断其所属的保养项目明细
            int deviceTypeInspectcount = deviceTypeMapper.countDeviceTypeInspectByMatTypeId(deviceTypeId);
            if(deviceTypeInspectcount>0){
                return JSONObject.build(JSONObject.ERROR,"所选设备类别下包含保养项目明细无法删除");
            }
            //判断其所属的点检项目明细
            int deviceTypeMainTainCount = deviceTypeMapper.countDeviceTypeMainTainByMatTypeId(deviceTypeId);
            if(deviceTypeMainTainCount>0){
                return JSONObject.build(JSONObject.ERROR,"所选设备类别下包含点检项目明细无法删除");
            }
            //判断设备信息是否
            int deviceCount = deviceTypeMapper.queryDeviceByDeviceTypeId(deviceTypeId);
            if(deviceCount>0){
                return JSONObject.build(JSONObject.ERROR,"所选设备类别关联设备信息无法删除");
            }
            int row = deviceTypeMapper.defineDeviceType(deviceTypeId,dataState);
            String msg = "";
            switch (dataState) {
                case 1:
                    msg = "启用";
                    break;
                case 2:
                    msg = "删除";
                    break;
                case 3:
                    msg = "停用";
            }
            if (row == 0) {
                // 判断传入的数据状态参数lDataState,返回相应信息
                switch (dataState) {
                    case 1:
                        return JSONObject.build(JSONObject.ERROR,msg+"失败");
                    case 2:
                        return JSONObject.build(JSONObject.ERROR,msg+"失败");
                    case 3:
                        return JSONObject.build(JSONObject.ERROR,msg+"失败");
                }
            }
            return JSONObject.oK(msg+"成功", row);
        }catch (GlobalException e){
            logger.error(e.getMessage());
            return JSONObject.build(JSONObject.ERROR, e.getMessage());
        }
    }

    /**
     * 树
     * @param deviceType
     * @return
     */
    @Override
    public JSONObject treeDeviceType(DeviceType deviceType) {
        List<XTreeNode> tree = null;
        try {
            tree = new ArrayList<>();
            List<XTreeNode> nodes = new ArrayList<>();
            //获取所有的物料类别进行构建树
            List<DeviceType> list = deviceTypeMapper.queryTreeDeviceType(deviceType);
            //构建一个标志,当其不为空的时候树上增加全部
            if(deviceType.getFlag()!=null){
                XTreeNode node0=new XTreeNode();
                DeviceType mx=new DeviceType();
                mx.setDeviceTypeId(0);
                mx.setDeviceTypePid(0);
                mx.setDeviceTypeName("全部");
                node0.setId(mx.getDeviceTypeId());
                node0.setpId(mx.getDeviceTypePid() == 0 ? null : mx.getDeviceTypePid());
                node0.setOpen(true);
                node0.setTitle(mx.getDeviceTypeName());
                list.add(0,mx);
            }
            //当标志大于0的时候,将其父的expand改为true,该树改为的selected改为true
            if (!list.isEmpty()) {
                for (DeviceType newDeviceType : list) {
                    XTreeNode node = new XTreeNode();
                    node.setId(newDeviceType.getDeviceTypeId());
                    node.setpId(newDeviceType.getDeviceTypePid() == 0 ? null : newDeviceType.getDeviceTypePid());
                    node.setOpen(true);
                    node.setCode(newDeviceType.getDeviceTypeCode());
                    node.setTitle(newDeviceType.getDeviceTypeName());
                    nodes.add(node);
                }
            }
            if(deviceType.getFlag()!=null && deviceType.getFlag()>0){
                if(deviceType.getFlag()>0){
                    List<XTreeNode> aBoolean = new XTreeUtil().getBoolean(deviceType.getFlag(), nodes);
                    //当页面初始化的时候为树的第一个默认是点亮的状态
                    tree = XCommonUtil.getTree(aBoolean, null);
                    return JSONObject.oK(tree);
                }
            }else{
                //当页面初始化的时候为树的第一个默认是点亮的状态
                tree = XCommonUtil.getTree(nodes, null);
                tree.get(0).setSelected(true);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONObject.oK(tree);
    }

    @Override
    public JSONObject queryAllDeviceType(DeviceType deviceType) {
        Integer pagesize = deviceType.getPagesize();
        Integer pageindex = deviceType.getPageindex();
        if(pagesize != null && pageindex != null) {
            deviceType.setIncept(pagesize*(pageindex - 1));
        }
        List<DeviceType> deviceTypeList = deviceTypeMapper.queryAllDeviceType(deviceType);
        if(!deviceTypeList.isEmpty()){
            int count = deviceTypeMapper.countAllDeviceType(deviceType);
            return JSONObject.oK("查询成功",deviceTypeList,count);
        }
        return JSONObject.oK("没有相关数据",deviceTypeList,null);
    }


    @Override
    public JSONObject filterMaintain(DeviceType deviceType) {
        Integer pageindex = deviceType.getPageindex();
        Integer pagesize = deviceType.getPagesize();
        if(pagesize != null && pageindex != null) {
            deviceType.setIncept(pagesize*(pageindex - 1));
        }
        Integer deviceTypeId = deviceType.getDeviceTypeId();
        if(deviceTypeId==null || "".equals(deviceTypeId)){
            //获取所有的物料类别进行构建树
            List<DeviceType> list = deviceTypeMapper.queryAllDeviceType(new DeviceType());
            deviceType.setDeviceTypeId(list.get(0).getDeviceTypeId());
        }
        List<DeviceType> deviceTypeList = deviceTypeMapper.filterMaintain(deviceType);
        if(!deviceTypeList.isEmpty()){
            int countFilterMaintain = deviceTypeMapper.countFilterMaintain(deviceType);
            return JSONObject.oK("查询成功",deviceTypeList,countFilterMaintain);
        }
        return JSONObject.oK("没有相关数据",deviceTypeList,null);
    }

    @Override
    public JSONObject filterInspect(DeviceType deviceType) {
        Integer pageindex = deviceType.getPageindex();
        Integer pagesize = deviceType.getPagesize();
        if(pagesize != null && pageindex != null) {
            deviceType.setIncept(pagesize*(pageindex - 1));
        }
        Integer deviceTypeId = deviceType.getDeviceTypeId();
        if(deviceTypeId==null || "".equals(deviceTypeId)){
            //获取所有的物料类别进行构建树
            List<DeviceType> list = deviceTypeMapper.queryAllDeviceType(new DeviceType());
            deviceType.setDeviceTypeId(list.get(0).getDeviceTypeId());
        }
        List<Inspect> inspectList = deviceTypeMapper.filterInspect(deviceType);
        if(!inspectList.isEmpty()){
            int countFilterInspect = deviceTypeMapper.countFilterInspect(deviceType);
            return JSONObject.oK("查询成功",inspectList,countFilterInspect);
        }
        return JSONObject.oK("没有相关数据",inspectList,null);
    }


    /**
     * 检测属性
     * @param deviceType
     */
    private  String checkElement(DeviceType deviceType){
        //设备类别编码
        String deviceTypeCode = deviceType.getDeviceTypeCode();
        //设备类别名称
        String deviceTypeName = deviceType.getDeviceTypeName();
        if(StringUtils.isEmpty(deviceTypeCode)){
            return "设备类别编号不能为空";
        }
        if(deviceTypeCode.length()>50){
            return "设备类别编号不能大于50";
        }
        if(StringUtils.isEmpty(deviceTypeName)){
            return "设备类别名称不能为空";
        }
        if(deviceTypeName.length()>50){
            return "设备类别名称不能大于50";
        }
        int deviceTypeCodeCount=deviceTypeMapper.queryDeviceTypeCode(deviceType);
        if(deviceTypeCodeCount>0){
            return "设备类别编号已存在";
        }
        int deviceTypeNameCount=deviceTypeMapper.queryDeviceTypeName(deviceType);
        if(deviceTypeNameCount>0){
            return "设备类别名称已存在";
        }
        return null;
    }
}
